package Dao;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JOptionPane;

public class Dao {
	
	protected static Connection conn = null;	
	/**
	 * 数据库链接配置
	 * @return 连接接口conn
	 * @throws Exception
	 */
	protected static Connection ConnectSqlite() throws Exception {	 
		 
		 File directory = new File("");
		 String projectPath = directory.getCanonicalPath(); //获取当前路径
		 try{		 
			 Class.forName("org.sqlite.JDBC");
		     conn = DriverManager.getConnection("jdbc:sqlite:"+projectPath+"/db/TextRank.db"); //设定数据库位置
		     tableIfNotExist();
		 }
		 catch ( Exception e ){
			 JOptionPane.showMessageDialog(null, e.getClass().getName() + ": " + e.getMessage());
		     System.exit(0);
		  	}
		 return conn;		     
	 }
	 
	/**
	 * 连接数据库后判断是否存在prdt表
	 * @throws Exception
	 */
	private static  void tableIfNotExist() throws Exception {
		 try{		 
			 String sql = "SELECT count(*) as A FROM sqlite_master WHERE type='table' AND name='prdt'"; //判断表是否存在的sql语句			      
			 Statement stmt = conn.createStatement();  
		     ResultSet rs = stmt.executeQuery(sql);
		     while(rs.next()){
		    	 if(rs.getInt(1) == 0){ //如果表不存在则创建
		    		 //ID列自增长，prd_Name名称，prd_No料号，pri金额
		    		 String sql2 = "CREATE TABLE prdt " +
		                     "(ID INTEGER PRIMARY  KEY     AUTOINCREMENT," +
		                     " prd_Name        TEXT    NOT NULL, " + 
		                     " prd_No          INT     NOT NULL, " + 
		                     " pri             REAL    NOT NULL)"; 
		    		 stmt.executeUpdate(sql2);
		    	 }
		     }		 
		 }catch(Exception e){
			 e.printStackTrace();
		 }	    
	 }

}
